package com.clay.appointment.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : clay
 * @Description:
 * @Date: Create in 17:39 2021/8/26
 * @Modified By:
 */
public class JwtHelper {
    private static long tokenExpiration = 30*60*1000;
    private static String tokenSignKey = "JWTHospitalAppointment";

    private JwtHelper()
    {

    }

    public static String createToken(Long userId, String userName) {
        Map<String, Object> headerMap =new HashMap<>();
        headerMap.put("alg","HS512");
        headerMap.put("typ","JWT");
        String token = Jwts.builder()
                .setHeader(headerMap)
                .setSubject("HOSPITAL-APPOINTMENT-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
//                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
//    public static String getUserName(String token) {
//        if(StringUtils.isEmpty(token)) {
//            return "";
//        }
//        Jws<Claims> claimsJws
//                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
//        Claims claims = claimsJws.getBody();
//        return (String)claims.get("userName");
//    }
}
